from fastapi import APIRouter, HTTPException
from app.services.article_service import (
    create_article,
    get_article_by_id,
    get_all_articles,
    update_article,
    delete_article
)

router = APIRouter(prefix="/articles", tags=["articles"])

@router.post("/")
async def create_article_api(title: str, content: str):
    """创建文章API"""
    article = create_article(title, content)
    if article:
        return {"message": "文章创建成功", "article_id": article.id}
    else:
        raise HTTPException(status_code=400, detail="文章创建失败")

@router.get("/{article_id}")
async def get_article_api(article_id: int):
    """获取文章详情API"""
    article = get_article_by_id(article_id)
    if article:
        return {
            "article": {
                "id": article.id,
                "title": article.title,
                "content": article.content,
                "created_at": article.created_at,
                "updated_at": article.updated_at
            }
        }
    else:
        raise HTTPException(status_code=404, detail="文章未找到")

@router.get("/")
async def get_all_articles_api():
    """获取所有文章API"""
    articles = get_all_articles()
    if articles:
        return {
            "articles": [
                {
                    "id": article.id,
                    "title": article.title,
                    "created_at": article.created_at,
                    "updated_at": article.updated_at
                } for article in articles
            ]
        }
    else:
        raise HTTPException(status_code=404, detail="获取文章列表失败")

@router.put("/{article_id}")
async def update_article_api(article_id: int, title: str, content: str):
    """更新文章API"""
    article = update_article(article_id, title, content)
    if article:
        return {"message": "文章更新成功"}
    else:
        raise HTTPException(status_code=404, detail="文章更新失败")

@router.delete("/{article_id}")
async def delete_article_api(article_id: int):
    """删除文章API"""
    if delete_article(article_id):
        return {"message": "文章删除成功"}
    else:
        raise HTTPException(status_code=404, detail="文章删除失败")